package com.bsj.power.pls.queue.service.impl.tactic;

import cn.hutool.core.util.HexUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bsj.power.common.config.cached.RedisCached;
import com.bsj.power.common.config.global.JsonResultEnum;
import com.bsj.power.common.config.redis.RTKConstant;
import com.bsj.power.common.constant.ApiConstants;
import com.bsj.power.common.http.ExternalAccessHttp;
import com.bsj.power.common.util.DataUtil;
import com.bsj.power.common.util.ExceptionUtil;
import com.bsj.power.pls.config.cached.HighRiseCached;
import com.bsj.power.pls.config.cached.OrderCounter;
import com.bsj.power.pls.config.net.netty.protocol.UWBAck;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author yinhao
 * @version 1.0
 * @description 数据消费类
 * @date 2024/10/18
 */
@Slf4j
@Component
public class RTKConsumeHandle {

    @Value("${myUrl.ipHost}")
    private String ipHost;
    @Value("${myUrl.rtk.sleep}")
    private Integer sleep;

    @Autowired
    private RedisCached redisCached;

    public void handle(byte[] bytes) {
        try {
            JSONArray tagDevList = getAllTagDevList(ipHost);
            if (tagDevList == null || tagDevList.size() == 0) {
                log.info("未获取到标签设备信息");
                return;
            }
            List<Integer> allMapId = HighRiseCached.getAllMapId();
            //过滤掉室外的mapId
            allMapId.remove(Integer.valueOf(33));
            allMapId.remove(Integer.valueOf(34));
            JSONArray outdoorDev = tagDevList.stream().filter(json -> !allMapId.contains(((JSONObject) json).getInteger("mapId")))
                    .collect(JSONArray::new, JSONArray::add, JSONArray::addAll);
            if (outdoorDev.size() == 0) {
                log.info("标签无室外设备");
                return;
            }
            int num = OrderCounter.getNum();
            redisCached.set(RTKConstant.RTK_BROADCAST_TEMP_KEY + num, HexUtil.encodeHexStr(bytes, false), 20);
            //将数据分包
            byte[][] divideData = DataUtil.divideData(bytes, 50);
            for (int i = 0; i < divideData.length; i++) {
                //当前包内容
                byte[] nowData = divideData[i];
                byte[] rtkSend = UWBAck.rtkSend(nowData, i + 1, divideData.length, num);
//                String rtkSendStr = HexUtil.encodeHexStr(rtkSend);
                //在每个包后面加入回车换行
                String rtkSendStr = HexUtil.encodeHexStr(rtkSend) + HexUtil.encodeHexStr("\r\n".getBytes());
                outdoorDev.stream().forEach(item -> {
                    JSONObject jsonObject = ((JSONObject) item);
                    Integer id = jsonObject.getInteger("id");
                    String sn = jsonObject.getString("sn");
                    Boolean online = jsonObject.getBoolean("online");
                    if (online == null) {
                        return;
                    }
                    //不在线也不发
                    if (!online) {
                        return;
                    }
                    boolean b = ExternalAccessHttp.transmitDataHttpPut("D", ipHost, id + "", rtkSendStr);
                    log.info("RTK数据广播下发, SN: {}, 透传状态: {}, 透传数据: {}", sn, b, rtkSendStr);
                });
//            boolean b = ExternalAccessHttp.transmitDataHttpPut(ipHost, 4 + "", rtkSendStr);
//            log.info("RTK数据广播下发, SN: {}, 透传状态: {}, 透传数据: {}", "11917701561780407820", b, rtkSendStr);
                Thread.sleep(sleep);
            }
        } catch (Exception e) {
            log.error("RTKConsumeHandle 数据消费失败: {}", ExceptionUtil.getStackStr(e));
            return;
        }
    }

    /**
     * 获取标签设备信息
     *
     * @param address
     * @return
     */
    private static JSONArray getAllTagDevList(String address) {
        String str = HttpUtil.get(address + ApiConstants.GET_ALL_TAG);
        if (StringUtils.isBlank(str)) {
            return null;
        }
        JSONObject result = JSONObject.parseObject(str);
        if (!result.getInteger("code").equals(JsonResultEnum.SUCCESS.getCode())) {
            return null;
        }
        JSONArray jsonArray = result.getJSONArray("data");
        return jsonArray;
    }

    /**
     * 循环数据发送
     * @param bytes
     */
    public void handleCycle(byte[] bytes, int num) {
        try {
            JSONArray tagDevList = getAllTagDevList(ipHost);
            if (tagDevList == null || tagDevList.size() == 0) {
                log.info("未获取到标签设备信息");
                return;
            }
            List<Integer> allMapId = HighRiseCached.getAllMapId();
            //过滤掉室外的mapId
            allMapId.remove(Integer.valueOf(33));
            allMapId.remove(Integer.valueOf(34));
            JSONArray outdoorDev = tagDevList.stream().filter(json -> !allMapId.contains(((JSONObject) json).getInteger("mapId")))
                    .collect(JSONArray::new, JSONArray::add, JSONArray::addAll);
            if (outdoorDev.size() == 0) {
                log.info("标签无室外设备");
                return;
            }
//            int num = OrderCounter.getNum();
//            redisCached.set(RTKConstant.RTK_BROADCAST_TEMP_KEY + num, HexUtil.encodeHexStr(bytes, false), 20);
            //将数据分包
            byte[][] divideData = DataUtil.divideData(bytes, 50);
            for (int i = 0; i < divideData.length; i++) {
                //当前包内容
                byte[] nowData = divideData[i];
                byte[] rtkSend = UWBAck.rtkSend(nowData, i + 1, divideData.length, num);
                String rtkSendStr = HexUtil.encodeHexStr(rtkSend);
                outdoorDev.stream().forEach(item -> {
                    JSONObject jsonObject = ((JSONObject) item);
                    Integer id = jsonObject.getInteger("id");
                    String sn = jsonObject.getString("sn");
                    Boolean online = jsonObject.getBoolean("online");
                    if (online == null) {
                        return;
                    }
                    //不在线也不发
                    if (!online) {
                        return;
                    }
                    boolean b = ExternalAccessHttp.transmitDataHttpPut("D", ipHost, id + "", rtkSendStr);
                    log.info("RTK数据广播下发, SN: {}, 透传状态: {}, 透传数据: {}", sn, b, rtkSendStr);
                });
                Thread.sleep(500);
            }
        } catch (Exception e) {
            log.error("RTKConsumeHandle 数据消费失败: {}", ExceptionUtil.getStackStr(e));
            return;
        }
    }

    public static void main(String[] args) throws Exception{
        byte[] b1 = "\r\n".getBytes();
        byte[] b2 = "\r\n".getBytes("GBK");
        System.out.println(HexUtil.encodeHexStr(b1));
        System.out.println(HexUtil.encodeHexStr(b2));
    }
}
